from rest_framework.views import APIView
from rest_framework.viewsets import ViewSet,GenericViewSet,ModelViewSet
from rest_framework.decorators import action
from rest_framework import serializers

from django.conf import settings
from django.core.paginator import Paginator
from django.db.models import Q

from main.report.models import DataSource, DataTable, TableColumn, TableColumnMapping, TableMapping
from main.utils.util_db import MySqlHandler
from main.utils.util_response import SuccessResponse, DetailResponse
import main.migrates.sql as table_sql



handler = MySqlHandler(settings.DB_INSTANCE)



class DataTableSerializer(serializers.ModelSerializer):
    # update_datetime=serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', write_only=True)
    class Meta:
        model = DataTable
        fields ='__all__'

    
class TableColumnSerializer(serializers.ModelSerializer):
    column_name = serializers.CharField(source='name')
    column_comment = serializers.CharField(source='desc')
    is_nullable = serializers.CharField(source='get_is_nullable_display')
    is_primary_key = serializers.CharField(source='get_is_primary_key_display')
    class Meta:
        model = TableColumn
        fields ='__all__'


class TableView(ViewSet):

    @action(methods=['post'], detail=False, url_path="list")
    def get_table_list(self, request):
        pageSize = request.data.get('limit')
        currentPage = request.data.get('page')
        table_name = request.data.get('table_name')
        table_comment = request.data.get('table_comment')
        objs = DataTable.objects.filter(Q(table_name__contains=table_name)|Q(table_desc__contains=table_comment))
        # return DetailResponse(msg="获取元数据-表信息", data=ser.data)
        p =Paginator(objs, pageSize)
        objs = p.get_page(currentPage).object_list
        ser = DataTableSerializer(objs, many=True)
        return SuccessResponse(msg="获取元数据-表信息",data=ser.data,total=p.count,page=currentPage,limit=pageSize)

    
    @action(methods=['post'], detail=False, url_path='detail')
    def get_table_detail(self, request):
        table_id =request.data.get("table_id")
        # items = [item for item in handler.query("select * from etl_ctl_column_relation t where t.table_name = %s", (table_name,))]
        table=DataTable.objects.get(id=table_id)
        obj = TableColumn.objects.filter(table_id = table_id)
        ser = TableColumnSerializer(obj, many=True)
        return DetailResponse(msg="获取元数据-字段信息", data = ser.data)
    
    # @action(methods=['get'], detail=False, url_path="column")
    # def get_table_column(self, request):
    #     table_name =request.query_params.get("tablename")
    #     return DetailResponse(msg="获取元数据-字段信息", data=handler.query("select * from etl_ctl_column_relation t where t.table_name = %s", (table_name,)))
        
class TableColumnView(ModelViewSet):
    queryset = TableColumn.objects.all()
    serializer_class = TableColumnSerializer
        
class DataSourceView(GenericViewSet):
    def get(self, request):
        handler = MySqlHandler(settings.DB_INSTANCE)
        items = [item for item in handler.query( table_sql.SQL_DB_INFO)]
        db_server = request.query_params.get('db_server')
        db_type = request.query_params.get('db_type')
        if db_type:
            items = [item for item in items if item['db_type'] == db_type]
            # 指定返回的字段
            columns = ['db_type', 'db_name']
            items = [dict(zip(columns, [item.get('db_type'),item.get('db_name')])) for item in items]
        else:
            columns = ['db_type']
            items = set([item.get('db_type') for item in items])
            items = [dict(zip(columns, [item])) for item in items]
        return DetailResponse(data=items)


class MappingView(ViewSet):
    @action(methods=['post'], detail=False, url_path="list")
    def get_table_list(self, request):
        pageSize = request.data.get('limit')
        currentPage = request.data.get('page')
        table_name = request.data.get('table_name')
        table_comment = request.data.get('table_comment')
        items = [item for item in handler.query( table_sql.SQL_TABLE_MAPPING)]
        if table_comment !='':
            items = [item for item in items if table_comment in item['table_comment']]
        if table_name !='':
            items = [item for item in items if table_name in item['table_name']]
        # 使用分页查询器
        p =Paginator(items, pageSize)
        dataList = p.get_page(currentPage).object_list
        return SuccessResponse(data=dataList,total=p.count,page=currentPage,limit=pageSize)
